package com.wxiao.exam.controller;

import com.wxiao.exam.DataUtils;
import com.wxiao.exam.Result;
import com.wxiao.exam.pojo.ManagerDO;
import com.wxiao.exam.pojo.StudentDO;
import com.wxiao.exam.pojo.TeacherDO;
import com.wxiao.exam.realm.UsernamePasswordTypeToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @RequestMapping("/login")
    public String index() {
        return "login";
    }

    /**
     * 学生教师 管理员登录
     *
     * @param username
     * @param password
     * @param role
     * @param httpSession
     * @return
     */
    @RequestMapping(value = "/login/do", method = RequestMethod.POST)
    public String login(String username, String password, String role, HttpSession httpSession, Model model) {
        Subject subject = SecurityUtils.getSubject();
        try {
            switch (role) {
                case "1": {//学生
                    subject.login(new UsernamePasswordTypeToken(username, password, UsernamePasswordTypeToken.STUDENT));
                    StudentDO student = (StudentDO) subject.getPrincipal();
                    httpSession.setAttribute("student", student);
                    return "student/index";
                }
                case "2": {
                    subject.login(new UsernamePasswordTypeToken(username, password, UsernamePasswordTypeToken.TEACHER));
                    TeacherDO teacher = (TeacherDO) subject.getPrincipal();
                    httpSession.setAttribute("teacher", teacher);
                    return "teacher/index";
                }
                case "3": {
                    subject.login(new UsernamePasswordTypeToken(username, password, UsernamePasswordTypeToken.ADMIN));
                    ManagerDO manager = (ManagerDO) subject.getPrincipal();
                    httpSession.setAttribute("manager", manager);
                    return "admin/index";
                }
            }
        } catch (AuthenticationException e) {
            e.printStackTrace();
            model.addAttribute("error", "用户名或密码错误");
            return "login";
        }
        return "login";
    }


    @RequestMapping("/login/verify")
    @ResponseBody
    public Result verify(String verify, HttpSession session) {
        return DataUtils.checkVerify(verify, session);
    }
}
